# coding: utf-8
import time
import json
import re
from datetime import datetime
from StringIO import StringIO
from flask import Blueprint, render_template, request, session
from tools import logging, wrapsfuncs
from dbModels import (AgmKf, WechatUser, Log_Wechat_Message, Log_Wechat_Event, 
    Wechat_Reply_Message, WechatKfLog, AgmSellVerifyProduct
)
from leancloud import Query, Object, File
from agmbeta import agmbeta_view, printDateTime, ISLOCAL, DEALERCONFIGID, wxjs_sign

@agmbeta_view.route('/kfclose', methods=['POST', 'GET'])
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission(['agmadmin', 'agmkf'])
def kf_close():
    from tools.wechatAPI import getkflist, getkfsessionlist, getkfsession, closekf
    if request.method == 'POST':
        action = request.args.get('action')
        if action == 'closekf':
            openid = request.args.get('openid')
            kfsession = getkfsession(openid)
            kf_account = kfsession['kf_account']
            ret = closekf(openid, kf_account)
            return 'success'
    kfs = []
    if session.get('wechatrole') == 'agmkf':
        openid = session.get('openid')
        user = Query(AgmKf).equal_to('openid', openid).find()
        if user:
            user = user[0]
            kfaccount = user.get('kfaccount')
            if kfaccount:                
                kfs = [kfaccount]
    else:
        olkfs = getkflist(True)
        for kf in olkfs:
            if kf.get('accepted_case') != 0:
                kfs.append(kf['kf_account'])
    sessionlist = []
    for kf in kfs:
        sessionlist.extend(getkfsessionlist(kf)['sessionlist'])
    openids = [t.get('openid') for t in sessionlist]
    users = Query(WechatUser).contained_in('openid', openids).find() if openids else []
    user_dict = {}
    for u in users:
        user_dict[u.get('openid')] = {
            'nickname': u.get('nickname_emoji') or u.get('nickname'),
            'headimgurl': u.get('headimgurl')
        }
    # print user_dict
    
    return render_template('agm1.0/kf/agm_kf_close.html', openids=openids, user_dict=user_dict)    
    
    
    
@agmbeta_view.route('/kflink', methods=['POST', 'GET'])
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission(['agmadmin'])
def kf_link():
    from tools.wechatAPI import getkfsdict
    if request.method == 'POST':
        action = request.args.get('action')
        if action == 'kflink':
            openid = request.args.get('openid')
            kfaccount = request.args.get('kfaccount')
            if openid and kfaccount:
                user = Query(AgmKf).equal_to('openid', openid).find()
                if user:
                    user = user[0]
                    if kfaccount == '0':
                        user.unset('kfaccount').save()
                    else:
                        user.set('kfaccount', kfaccount).save()
                    return 'success'
        return 'Kf_linkPost'
    kfsdict = getkfsdict()
    kfaccounts = sorted(kfsdict.keys())
    kfs = Query(AgmKf).find()
    
    return render_template('agm1.0/kf/agm_kf_link.html', kfs=kfs, kfaccounts=kfaccounts)  

@agmbeta_view.route('/kfchat', methods=['POST', 'GET'])
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission(['agmadmin', 'agmkf'])
def kf_chat():
    if request.method == 'POST':
        action = request.args.get('action')
        if action == 'sendmessage':
            reply_openid = request.args.get('openid')
            message = request.form.get('message')
            if reply_openid:
                from tools.wechatAPI import sendmessage, getkfsdict, sendableUserOpenids
                openid = session.get('openid')
                if ISLOCAL:
                    openid = 'ohCrcvq5TTqoF1eP4p2oLn6rte2k'
                if openid:
                    kfaccount = getkfaccount(openid) or ''
                    if session.get('wechatrole') != 'agmadmin':
                        if not kfaccount:
                            return json.dumps({'error': 'NoLinkAccount'})
                            # return 'NoLinkAccount' 
                    sendable = sendableUserOpenids(openid=reply_openid)
                    if sendable is False:
                        return json.dumps({'error': 'limit_timeout'})
                    if sendable is None:
                        return json.dumps({'error': 'unsubscribe'})
                    ctime = int(time.time())
                    ret = sendmessage(reply_openid, message, fromkf=kfaccount)
                    if ret['errcode'] == 45015:
                        return json.dumps({'error': 'limit_timeout'})
                    data = dict(openid=reply_openid, Content=message, CreateTime=ctime, kfaccount=kfaccount)
                    if kfaccount:
                        kfsdict = getkfsdict()
                        if kfaccount not in kfsdict:
                            kfsdict = getkfsdict(True)
                        data['kf_nick'] = kfsdict[kfaccount].get('kf_nick', '')
                        data['kf_headimgurl'] = kfsdict[kfaccount].get('kf_headimgurl_cache', '')
                    Wechat_Reply_Message(**data).save()
                    data['CreateTime'] = printDateTime(ctime, '%Y-%m-%d %H:%M:%S', False, True)
                    ret = {
                        'nickname': data.get('kf_nick', ''),
                        'headimgurl': data.get('kf_headimgurl', ''),
                        'strtime':data['CreateTime'],
                        'content':data['Content']
                    }
                    return json.dumps(ret)
                return 'NoOpenid'
        elif action == 'getvoice':
            from tools.wechatAPI import sendmessage, sendableUserOpenids
            openid = session.get('openid')
            if ISLOCAL:
                openid = 'ohCrcvlQMzCovAxALwzdNOs8yNf8'
            voiceid = request.args.get('voiceid')
            ret = sendmessage(openid, voiceid, 'voice')
            if ret['errcode'] == 45015:
                return 'timeout_or_unsubscribe'
            if ret['errcode'] == 0:
                return 'success'
            return ret['errmsg']
                
        elif action == 'loadmessages':
            end_time = request.args.get('end_time')
            uid = request.args.get('uid')
            user = Query(WechatUser).get(uid)
            messages, ismore = combineMessage(user, end_time=end_time)
            ret = {'messages': messages, 'openid': user.get('openid')}
            if ismore:
                ret['start_time'] = messages[-1].get('CreateTime')
            return json.dumps(ret)                        
       
        return 'kf_chat_POST'    

    from tools.wechatAPI import getaccesstoken, getkfsdict
    we_ac = getaccesstoken()
    kfsdict = getkfsdict()
    return render_template('agm1.0/kf/agm_kf_chat.html', 
        we_ac=we_ac, kfsdict=json.dumps(kfsdict)
    )    

@agmbeta_view.route('/kfchatuser', methods=['POST', 'GET'])
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission(['agmadmin', 'agmkf'])
def kf_chat_user():
    from tools.wechatAPI import sendableUserOpenids, get_save_userinfo_api
    if request.method == 'POST':
        action = request.args.get('action')
        if action == 'refrehuser':
            openid = request.args.get('openid')
            user = get_save_userinfo_api(openid)
            return json.dumps({
                'nickname': user.get('nickname_emoji') or user.get('nickname'), 
                'headimgurl': user.get('headimgurl')
            })
    if session.get('wechatrole') != 'agmadmin':
        sendabledict = sendableUserOpenids(True)
        openids = sendabledict['openids']
    else:
        sendabledict = sendableUserOpenids()
        openids = sendabledict['openids']
        openids.sort(key=lambda x:sendabledict['info'][x][1], reverse=True)
    users = Query(WechatUser).contained_in('openid', openids).find()
    users.sort(key=lambda x:openids.index(x.get('openid')))
    now = int(time.time())
    return render_template('agm1.0/kf/agm_kf_chat_user.html', 
        users=users, 
        now=now, 
        convertTime=convertTime, 
        info=sendabledict['info']
    )
    
def convertTime(t, now):
    limit = 48*60*60 # 48 hours
    remain = limit - (now-t)
    hour = remain/3600
    min = remain%3600/60
    sec = remain%60
    return hour, min, sec
    
def getkfaccount(openid):
    user = Query(AgmKf).equal_to('openid', openid).find()
    if user:
        user = user[0]
        return user.get('kfaccount')

def combineMessage(user, start_time=None, end_time=None):
    openid = user.get('openid')
    #公众号消息
    not_contains_content = ['1', '2', '3', '4', '5', '申请销售', '申请音速风暴客服']
    query = Query(Log_Wechat_Message).not_contained_in('Content', not_contains_content)
    query.equal_to('FromUserName', openid).descending('CreateTime')
    if start_time:
        query.greater_than('CreateTime', int(start_time))  
    if end_time:
        query.less_than('CreateTime', int(end_time))        
    limit = 10
    query.limit(limit)
    log_messages = query.find()
    ismore = len(log_messages) >= limit
    start_time = log_messages[-1].get('CreateTime') if log_messages else None
    #公众号事件
    query = Query(Log_Wechat_Event).equal_to('EventKey', 'contactkf')
    query.equal_to('FromUserName', openid).descending('CreateTime')
    if start_time:
        query.greater_than('CreateTime', int(start_time))  
    if end_time:
        query.less_than('CreateTime', int(end_time))        
    query.limit(limit)
    log_event = query.find()   
    ismore = len(log_event) >= limit if not ismore else True
    #客服消息(客服系统)
    # print openid, start_time, end_time
    hasmessage = True if log_messages + log_event else False
    kf_messages = getUserKfRecord(openid, start_time, end_time, hasmessage)
    # print kf_messages
    #客服回复消息(非客服系统)
    query = Query(Wechat_Reply_Message).equal_to('openid', openid)
    if start_time:
        query.greater_than('CreateTime', int(start_time))
    if end_time:
        query.less_than('CreateTime', int(end_time))
    replay_messages = query.find()
    messages = []
    media_expire = int(time.time()) - 60*60*24*3  # 3 days
    for t in (log_messages + replay_messages + log_event + kf_messages):
        createtime = t.get('CreateTime')
        if t.get('worker'):
            createtime = t.get('time')
            if t.get('opercode') == 2003:
                m = {
                    'nickname': user.get('nickname_emoji') or user.get('nickname'),
                    'headimgurl': user.get('headimgurl') or '/static/images/getheadimg.png',
                    'content': t.get('text')
                }
            else:
                m = {
                    'nickname': t.get('worker'),
                    'content': t.get('text'),
                    'iskf': True
                } 
            m['kfsystem'] = True
        elif t.get('openid'):
            m = {
                'nickname': t.get('kf_nick'),
                'headimgurl': t.get('kf_headimgurl'),
                'iskf': True,
                'content': t.get('Content')
            }
        else:
            m = {
                'nickname': user.get('nickname_emoji') or user.get('nickname'),
                'headimgurl': user.get('headimgurl') or '/static/images/getheadimg.png',
            }
            if t.get('EventKey'):
                m['content'] = '[点击-人工服务]'
            elif t.get('MsgType') == 'text':
                m['content'] = t.get('Content')
            elif t.get('MsgType') == 'image':
                if t.get('CreateTime') < media_expire:
                    m['imgid'] = 'expire'
                else:
                    m['imgid'] = t.get('MediaId')
            elif t.get('MsgType') == 'voice':
                if t.get('CreateTime') < media_expire:
                    m['voiceid'] = 'expire'
                else:
                    m['voiceid'] = t.get('MediaId')
            else:
                m['content'] = '[%s]' % t.get('MsgType')
        m['CreateTime'] = createtime
        m['strtime'] = printDateTime(createtime, '%Y-%m-%d %H:%M:%S', False, True)
        messages.append(m)        
    messages.sort(key=lambda x:x.get('CreateTime'), reverse=True)
    return messages, ismore

def getUserKfRecord(openid, start_time, end_time, hasmessage):
    query = Query(WechatKfLog).equal_to('openid', openid)
    if start_time:
        query.greater_than('time', int(start_time))
    if end_time:
        query.less_than('time', int(end_time))
    # print query.dump()
    messages = query.find()
    if not end_time or int(end_time) > time.mktime(datetime.today().timetuple()) and hasmessage:
        from tools.wechatAPI import getkfrecord
        kfmessage = getkfrecord()['recordlist']
        for t in kfmessage:
            if t.get('openid') == openid:
                messages.append(t)
    return messages    
    
@agmbeta_view.route('/sellverify', methods=['POST', 'GET'])
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission(['agmadmin', 'agmsell'])
def sellverify():
    if request.method == 'POST':
        action = request.args.get('action')
        if action == 'sellpostimage':
            openid = session.get('openid')
            if ISLOCAL:
                openid = 'ohCrcvq5TTqoF1eP4p2oLn6rte2k'
            try:
                image = request.files.get('imgfile')
            except:
                return 'TooLarge'
            pname = request.form.get('pname')
            fwcode = request.form.get('fwcode')
            if not pname or not image:
               return 'argsError'
            if not image.content_type.startswith('image'):
                return 'uploadnotimage' 
            filename = image.filename
            imagedata = StringIO(image.stream.read())
            lfile = File(filename, imagedata)
            AgmSellVerifyProduct(openid=openid, imgfile=lfile, pname=pname, fwcode=fwcode).save() 
            return 'success'
        elif action == 'submitpost':
            imageids = request.form.get('imageids')
            openid = session.get('openid')
            if ISLOCAL:
                openid = 'ohCrcvq5TTqoF1eP4p2oLn6rte2k'
            pname = request.args.get('pname')
            fwcode = request.args.get('fwcode')
            if imageids and openid and pname:
                from tools.wechatAPI import getimagedata
                imageids = imageids.split(',')
                for imageid in imageids:
                    ret = getimagedata(imageid)
                    filename = re.search('filename="(.+?)"', ret.headers.get('Content-disposition')).group(1)
                    imagedata = StringIO(ret.read())
                    lfile = File(filename, imagedata)
                    AgmSellVerifyProduct(openid=openid, imgfile=lfile, pname=pname, fwcode=fwcode).save()
                return 'success'
            else:
                return 'argsError'
            
            return 'Done2 with %s, %s' % (image, pname)  
    wxjs_sign()
    dealerconfig = Query(Object.extend('Cache_dict')).get(DEALERCONFIGID).get('content')
    pnames = sorted(dealerconfig['defaultrule'].keys())
    return render_template('agm1.0/seller/agm_sell_verify.html', pnames=pnames)    
    
@agmbeta_view.route('/shoporder', methods=['POST', 'GET'])
@logging.log
@logging.agmlog
@wrapsfuncs.wxauth_permission(['agmadmin', 'agmsell'])
def shoporder():
    oid = request.args.get('oid')
    if oid:
        from tools.wechatAPI import get_order_detail
        order = get_order_detail(oid)['order']
        status_text = {
            '2': u'待发货', 
            '3': u'已发货', 
            '5': u'已完成',
            '6': u'已关闭'
        }
        status_i = {
            '2': u'waiting', 
            '3': u'success', 
            '5': u'success',
            '6': u'success-no-circle'
        }
        delivery_text = {
            '066zhongtong': u'中通速递',
            'Fsearch_code': u'邮政 EMS',
            '002shentong': u'申通速递',
            '056yuantong': u'圆通速递',
            '042tiantian': u'天天快递',
            '003shunfeng': u'顺丰速运',
            '059Yunda': u'韵达快运',
            '064zhaijisong': u'宅急送',
            '020huitong': u'汇通快运',
            'zj001yixun': u'易迅快递'
        }
        
        return render_template('agm1.0/agm_shop_order.html', order=order, status_text=status_text, status_i=status_i, str=str, delivery_text=delivery_text, fromtimestamp=datetime.fromtimestamp)
    else:
        from tools.wechatAPI import get_orders
        order_list = get_orders(2)['order_list']
        strtime = lambda x:datetime.fromtimestamp(x).strftime('%Y-%m-%d %H:%M:%S')

        return render_template('agm1.0/agm_shop_orders.html', orders=order_list, strtime=strtime)
    
@agmbeta_view.route('/order_notific', methods=['POST', 'GET'])
@logging.log
@logging.agmlog
#@wrapsfuncs.wxauth_permission(['agmadmin', 'agmkf'])
def order_notific():
    args = ['addr', 'mobile', 'total_count', 'product_name',
            'member', 'oid', 'receiver_name', 'ship_company',
            'order_total_price']
    int_arg = ['order_total_price']
    order = {}
    for arg in args: 
        if not request.form.get(arg):
            return "args error!"
        order[arg] = request.form.get(arg) 
        if arg in int_arg:
            order[arg] = float(order[arg])
    if len(order["product_name"]) > 30:
        order["product_name"] = order["product_name"][:30] + "..."
    from tools.wechatAPI import send_agm_order
    openids = ['ohCrcvlQMzCovAxALwzdNOs8yNf8']
    for openid in openids:
        send_agm_order(openid, order) 
    return "done"
    #order['addr'] = u'测试收货地址'
    #order['mobile'] = u'测试电话'
    #order['total_count'] = 2
    #order['product_name'] = u'测试货号'
    #order['member'] = u'测试用户名'
    #order['oid'] = u'测试单号'
    #order['receiver_name'] = u'测试收件人'
    #order['ship_company'] = u'测试货运公司'
    #order['order_total_price'] = 100
